from flask import g, jsonify
from flask_restful import reqparse
from utils.jwt_tool import JwtTool


# 检测登录的函数
def check_login():
    req = reqparse.RequestParser()
    req.add_argument("token", default="", location="headers")

    args = req.parse_args()
    token = args["token"]

    jwt_obj = JwtTool()
    payload = jwt_obj.ver_token(token)

    g.user = payload


# 检测登录的装饰器
def login(func):
    def wrapper(*args, **kwargs):
        # 装饰器代码
        check_login()
        return func(*args, **kwargs)

    return wrapper


# 强制验证token
def require_login(func):
    def wrapper(*args, **kwargs):
        user = g.user
        if not user:
            return jsonify({
                "code": 400,
                "msg": "Token已过期"
            })
        return func(*args, **kwargs)

    return wrapper
